package com.xjh.basestudy.javabase.javaweb.jdbc;



import com.xjh.basestudy.javabase.javaweb.jdbc.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcAccountDemo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            //1.获取连接
            conn = JDBCUtils.getConnecttion();
            //开启事务
            conn.setAutoCommit(false);
            //2.定义sql
            //2.1张三-500
            String sql1 = "update account set balance = balance - ? where id = ?";

            //2.2李四+500
            String sql2 = "update account set balance = balance + ? where id = ?";
            //3.获取执行sql对象
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            //4.设置参数
            pstmt1.setDouble(1, 500);
            pstmt1.setInt(2, 1);
            pstmt2.setDouble(1, 500);
            pstmt2.setInt(2, 1);
            //执行sql
            pstmt1.executeUpdate();
            //手动制造异常,在这里制造异常，会导致1减去，但是2没有加上
            int i = 3 / 0;
            pstmt2.executeUpdate();


        } catch (Exception e) {//不管出现什么异常都会滚，所以手动把异常改成Excepton
            //事务回滚
            try {
                if (conn != null) {//当conn不等于null（获取到对象）的时候才回滚
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.close(null, pstmt1, conn);
            JDBCUtils.close(null, pstmt2, null);
        }

    }
}
